package org.paradise.dms.web.tools;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 
 * Description:系统资源过滤器
 * 
 * Copyright (c) 2008-2009 paraDise sTudio(DT). All Rights Reserved.
 * 
 * @version 1.0 Apr 11, 2009 6:00:44 AM 李双江（paradise.lsj@gmail.com）created
 */
public class ResourceFilter extends HttpServlet implements Filter {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2037859724640227270L;
	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(ResourceFilter.class);
	private FilterConfig filterConfig;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
		try {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			boolean isValid = true;
			String uriStr = httpRequest.getRequestURI();
			// log.info("DMS_info:Session里面的用户为：" +
			// httpRequest.getSession().getAttribute("systemusername"));
			// log.info("indexOf Action is" + uriStr.indexOf(".action"));
			if (uriStr.indexOf(".jsp") == -1 && uriStr.indexOf(".action") == -1) {// 非请求jsp或者action，如调用dwr或者jpg,png资源，放行
				// log.info("isValid吗 ？=" + isValid);
				isValid = true;
			} else if (uriStr.indexOf("login.jsp") == -1 && uriStr.indexOf("login.action") == -1 && httpRequest.getSession().getAttribute("systemusername") == null) {
				// 小样，在session为null的情况下直接访问非登录页(login.jsp/action)并且不是请求png,dwr等资源，当然不让过了
				// log.info("所有发出的非登录的请求...");
				isValid = false;
			}
			if (isValid) {
				request.setCharacterEncoding("UTF-8");
				// log.info("doFilter 放行了..");
				filterChain.doFilter(request, response);
			} else {
				request.setCharacterEncoding("UTF-8");
				PrintWriter out = httpResponse.getWriter();
				String urlstring = httpRequest.getContextPath() + "/login.jsp";
				out.write("<script>window.top.location.href ='" + urlstring + "'</script>");
			}

		} catch (ServletException sx) {
			filterConfig.getServletContext().log(sx.getMessage());
		} catch (IOException iox) {
			filterConfig.getServletContext().log(iox.getMessage());
		}
	}

	public void destroy() {
	}
}
